package main

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"

	"github.com/jacobsa/go-serial/serial"
)

//程序配置
type Config struct {
	Serial_Opt serial.OpenOptions
	Net_Opt    NetOption
}

var AppConfig = Config{
	Serial_Opt: serial.OpenOptions{
		PortName:        "",
		BaudRate:        115200,
		DataBits:        8,
		StopBits:        1,
		ParityMode:      serial.PARITY_NONE,
		MinimumReadSize: 8,
	},
	Net_Opt: NetOption{
		IP:   "127.0.0.1",
		Port: 5200,
	},
}

const CONFIG_FILE = "conf.json"

//读取配置文件
func Read_config() bool {
	_, err := os.Stat(CONFIG_FILE)
	if err != nil {
		Write_config()
		log.Printf("配置文件[conf.json]不存在，将自动生成默认配置。\n错误:%v\n", err.Error())
		return false
	}
	cnf_jsn, err := ioutil.ReadFile(CONFIG_FILE)
	if err != nil {
		log.Printf("读取配置文件错误:%v\n", err.Error())
		return false
	}
	cnf_jsn = bytes.TrimSpace(cnf_jsn)
	if cnf_jsn[0] == byte('{') && cnf_jsn[len(cnf_jsn)-1] == byte('}') {
		err = json.Unmarshal(cnf_jsn, &AppConfig)
		if err != nil {
			log.Printf("配置文件转换错误:%v\n", err.Error())
			return false
		}
	}
	return true
}

//写入配置文件
func Write_config() {
	conf_jsn, err := json.MarshalIndent(AppConfig, "", "\t")
	if err != nil {
		log.Printf("配置序列化错误:%v\n", err.Error())
		return
	}
	err = ioutil.WriteFile(CONFIG_FILE, conf_jsn, os.ModePerm)
	if err != nil {
		log.Printf("配置文件写入错误:%v\n", err.Error())
	}
}
